// 模拟好友数据
const friends = [
    { id: 1, name: "张三", avatar: "https://picsum.photos/id/1001/40/40", unread: 0 },
    { id: 2, name: "李四", avatar: "https://picsum.photos/id/1002/40/40", unread: 2 },
    { id: 3, name: "王五", avatar: "https://picsum.photos/id/1003/40/40", unread: 0 },
    { id: 4, name: "赵六", avatar: "https://picsum.photos/id/1004/40/40", unread: 1 },
    { id: 5, name: "孙七", avatar: "https://picsum.photos/id/1005/40/40", unread: 0 },
    { id: 6, name: "周八", avatar: "https://picsum.photos/id/1006/40/40", unread: 0 },
    { id: 7, name: "吴九", avatar: "https://picsum.photos/id/1008/40/40", unread: 3 },
    { id: 8, name: "郑十", avatar: "https://picsum.photos/id/1012/40/40", unread: 0 }
];

// 模拟消息数据
const messages = {
    1: [
        { id: 1, sender: "me", content: "你好，最近怎么样？", time: "昨天 14:30", status: "read" },
        { id: 2, sender: "friend", content: "我很好，谢谢！你呢？", time: "昨天 14:32", status: "read" },
        { id: 3, sender: "me", content: "我也挺好的，最近在忙什么呢？", time: "昨天 14:35", status: "read" }
    ],
    2: [
        { id: 1, sender: "friend", content: "嗨，你看到我发给你的文件了吗？", time: "今天 09:15", status: "read" },
        { id: 2, sender: "me", content: "还没，我等会看一下", time: "今天 09:20", status: "read" },
        { id: 3, sender: "friend", content: "好的，麻烦尽快看一下", time: "今天 10:30", status: "sent" }
    ],
    3: [
        { id: 1, sender: "me", content: "周末要不要一起去打球？", time: "前天 18:20", status: "read" },
        { id: 2, sender: "friend", content: "好啊，我很乐意，什么时候？", time: "前天 18:30", status: "read" },
        { id: 3, sender: "me", content: "周六上午10点怎么样？", time: "前天 18:35", status: "read" },
        { id: 4, sender: "friend", content: "可以，我没问题", time: "前天 19:00", status: "read" }
    ]
};

// 模拟搜索结果
const searchResults = [
    { id: 1, friendId: 1, friendName: "张三", content: "你好，最近怎么样？", time: "昨天 14:30" },
    { id: 2, friendId: 3, friendName: "王五", content: "周末要不要一起去打球？", time: "前天 18:20" },
    { id: 3, friendId: 2, friendName: "李四", content: "嗨，你看到我发给你的文件了吗？", time: "今天 09:15" }
];

// 当前选中的好友ID
let currentFriendId = null;

// WebSocket连接
let ws = null;

$(document).ready(function() {
    // 初始化好友列表
    initFriendsList();

    // 初始化表情选择器
    initEmojiPicker();

    // 绑定事件
    bindEvents();

    // 连接WebSocket
    connectWebSocket();
});

// 初始化好友列表
function initFriendsList() {
    const friendsContainer = $("#friends");
    friendsContainer.empty();

    friends.forEach(friend => {
        const unreadBadge = friend.unread > 0
            ? `<span class="badge bg-primary rounded-pill">${friend.unread}</span>`
            : '';

        const friendItem = `
                    <div class="friend-item d-flex align-items-center ${friend.unread > 0 ? 'unread' : ''}" data-id="${friend.id}">
                        <img src="${friend.avatar}" alt="${friend.name}" class="friend-avatar">
                        <div class="flex-grow-1">
                            <div class="d-flex justify-content-between">
                                <h6 class="friend-name">${friend.name}</h6>
                                ${unreadBadge}
                            </div>
                            <p class="friend-message">${getLastMessage(friend.id) || '暂无消息'}</p>
                        </div>
                    </div>
                `;

        friendsContainer.append(friendItem);
    });

    // 绑定好友点击事件
    $(".friend-item").click(function() {
        const friendId = $(this).data("id");
        selectFriend(friendId);
    });
}

// 获取好友最后一条消息
function getLastMessage(friendId) {
    if (messages[friendId] && messages[friendId].length > 0) {
        return messages[friendId][messages[friendId].length - 1].content;
    }
    return null;
}

// 选择好友
function selectFriend(friendId) {
    // 移除之前选中好友的高亮
    $(".friend-item.active").removeClass("active");

    // 添加当前选中好友的高亮
    $(`.friend-item[data-id="${friendId}"]`).addClass("active");

    // 更新当前好友ID
    currentFriendId = friendId;

    // 更新当前好友名称
    const friend = friends.find(f => f.id === friendId);
    $("#current-friend-name").text(friend.name);

    // 显示聊天消息
    showMessages(friendId);

    // 隐藏空聊天提示
    $("#empty-chat").hide();

    // 重置未读消息数
    if (friend.unread > 0) {
        friend.unread = 0;
        initFriendsList();
    }
}

// 显示消息
function showMessages(friendId) {
    const messagesContainer = $("#chat-messages");
    messagesContainer.empty();

    if (!messages[friendId] || messages[friendId].length === 0) {
        messagesContainer.append(`
                    <div class="text-center text-muted py-5">
                        还没有消息，开始聊点什么吧
                    </div>
                `);
        return;
    }

    messages[friendId].forEach(message => {
        const isMyMessage = message.sender === "me";
        const avatar = isMyMessage
            ? "https://picsum.photos/id/1025/40/40"
            : friends.find(f => f.id === friendId).avatar;

        const messageClass = isMyMessage ? "message-right" : "";
        const contentClass = isMyMessage ? "bg-primary text-white" : "bg-light";
        const statusHtml = isMyMessage
            ? `<span class="message-status ${message.status === "read" ? "read" : ""}">
                        ${message.status === "read" ? "已读" : message.status === "sent" ? "已发送" : ""}
                    </span>`
            : '';

        let messageContent = message.message;
        // 如果是图片消息
        if (message.type === "image") {
            messageContent = `<img src="${message.message}" alt="图片消息" class="message-image">`;
        }

        const messageHtml = `
                    <div class="message ${messageClass}">
                        <img src="${avatar}" alt="${isMyMessage ? "我" : friends.find(f => f.id === friendId).name}" class="message-avatar">
                        <div>
                            <div class="message-content ${contentClass}">
                                ${messageContent}
                            </div>
                            <div class="d-flex justify-content-${isMyMessage ? "end" : "start"} mt-1">
                                <span class="message-time">${message.time}</span>
                                ${statusHtml}
                            </div>
                        </div>
                    </div>
                `;

        messagesContainer.append(messageHtml);
    });

    // 滚动到底部
    scrollToBottom();
}

// 发送消息
function sendMessage(content, type = "text") {
    if (!currentFriendId) {
        alert("请先选择一位好友");
        return;
    }

    const messageInput = $("#message-input");

    if (type === "text" && !content.trim()) {
        return;
    }

    // 创建新消息
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const time = `${hours}:${minutes}`;
    const to_uid = '3';
    const message_id = '3';
    const newMessage = {
        id: Date.now(),
        sender: "me",
        message: content,
        time: time,
        status: "sending",
        type: 'send_to_uid',
        to_uid:to_uid,
        message_id:message_id,
    };

    // 添加到消息列表
    if (!messages[currentFriendId]) {
        messages[currentFriendId] = [];
    }
    messages[currentFriendId].push(newMessage);

    // 显示消息
    showMessages(currentFriendId);

    // 清空输入框
    if (type === "text") {
        messageInput.val("");
    } else if (type === "image") {
        $("#image-upload").hide();
    }

    // 通过WebSocket发送消息
    if (ws && ws.readyState === WebSocket.OPEN) {
        const messageData = {
            type: "send_to_uid",
            to_uid: currentFriendId,
            message: content,
            message_type: type,
            message_id:0,
            uid:7
        };

        ws.send(JSON.stringify(messageData));

        // 更新消息状态为已发送
        setTimeout(() => {
            const index = messages[currentFriendId].findIndex(m => m.id === newMessage.id);
            if (index !== -1) {
                messages[currentFriendId][index].status = "sent";
                showMessages(currentFriendId);
            }
        }, 1000);
    } else {
        // 如果WebSocket连接失败，使用模拟发送
        console.log("WebSocket连接失败，使用模拟发送");

        // 模拟消息已发送
        setTimeout(() => {
            const index = messages[currentFriendId].findIndex(m => m.id === newMessage.id);
            if (index !== -1) {
                messages[currentFriendId][index].status = "sent";
                showMessages(currentFriendId);

                // 模拟对方回复
                if (Math.random() > 0.5) {
                    setTimeout(() => {
                        receiveMessage(currentFriendId, type === "image" ? "图片不错！" : "收到，谢谢！");
                    }, 1500);
                }
            }
        }, 1000);
    }
}

// 接收消息
function receiveMessage(friendId, message, type = "text") {
    // 创建新消息
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const time = `${hours}:${minutes}`;

    const newMessage = {
        id: Date.now(),
        sender: "friend",
        message: message,
        time: time,
        type: type
    };

    // 添加到消息列表
    if (!messages[friendId]) {
        messages[friendId] = [];
    }
    messages[friendId].push(newMessage);

    // 如果当前正在查看该好友的聊天，显示消息
    if (currentFriendId === friendId) {
        showMessages(friendId);

        // 标记消息为已读
        markMessagesAsRead(friendId);
    } else {
        // 否则增加未读计数
        const friend = friends.find(f => f.id === friendId);
        if (friend) {
            friend.unread++;
            initFriendsList();
        }
    }
}

// 标记消息为已读
function markMessagesAsRead(friendId) {
    if (ws && ws.readyState === WebSocket.OPEN) {
        const messageData = {
            type: "read",
            to: friendId
        };

        ws.send(JSON.stringify(messageData));
    }
}

// 滚动到底部
function scrollToBottom() {
    const chatMessages = $("#chat-messages");
    chatMessages.animate({ scrollTop: chatMessages.prop("scrollHeight") }, 300);
}

// 初始化表情选择器
function initEmojiPicker() {
    const emojiPicker = $("#emoji-picker");
    const emojis = [
        "😀", "😃", "😄", "😁", "😆",
        "😅", "😂", "🤣", "😊", "😇",
        "🙂", "🙃", "😉", "😌", "😍", "🥰",
        "😘", "😗", "😙", "😚", "🤩", "😳",
        "🥳", "😎", "🤓", "🧐", "😏", "😒",
        "😞", "😔", "😟", "😕", "🙁", "☹️",
        "😣", "😖", "😫", "😩", "🥺", "😢",
        "😭", "😤", "😠", "😡", "🤬", "🤯",
        "😳", "🥵", "🥶", "😱", "😨", "😰",
        "😓", "🤗", "🤔", "🤭", "🤫", "🤥",
        "😶", "😐", "😑", "😬", "🙄", "😯",
        "😦", "😧", "😮", "😲", "🥱", "😴",
        "🤤", "😪", "😵", "🤐", "🥴", "🤢",
        "🤮", "🤧", "😷", "🤒", "🤕" ,"😥"
    ];

    emojis.forEach(emoji => {
        const emojiElement = `<span class="emoji">${emoji}</span>`;
        emojiPicker.append(emojiElement);
    });

    // 绑定表情点击事件
    $(".emoji").click(function() {
        const emoji = $(this).text();
        const messageInput = $("#message-input");
        messageInput.val(messageInput.val() + emoji);
        messageInput.focus();
    });
}

// 搜索消息
function searchMessages(keyword) {
    const searchResultsContainer = $("#search-results");
    searchResultsContainer.empty();

    if (!keyword.trim()) {
        searchResultsContainer.append(`
                    <div class="text-center text-muted py-5">
                        输入关键词搜索消息
                    </div>
                `);
        return;
    }

    // 过滤搜索结果
    const filteredResults = searchResults.filter(result =>
        result.content.toLowerCase().includes(keyword.toLowerCase()) ||
        result.friendName.toLowerCase().includes(keyword.toLowerCase())
    );

    if (filteredResults.length === 0) {
        searchResultsContainer.append(`
                    <div class="text-center text-muted py-5">
                        没有找到相关消息
                    </div>
                `);
        return;
    }

    // 显示搜索结果
    filteredResults.forEach(result => {
        const resultHtml = `
                    <div class="mb-3 p-2 border rounded cursor-pointer" data-id="${result.friendId}">
                        <div class="d-flex align-items-center">
                            <img src="${friends.find(f => f.id === result.friendId).avatar}" alt="${result.friendName}" class="friend-avatar">
                            <div>
                                <h6 class="mb-0">${result.friendName}</h6>
                                <p class="mb-0 text-muted text-smaller">${result.time}</p>
                            </div>
                        </div>
                        <p class="mt-2 mb-0">${highlightKeyword(result.content, keyword)}</p>
                    </div>
                `;

        searchResultsContainer.append(resultHtml);
    });

    // 绑定搜索结果点击事件
    $("#search-results > div").click(function() {
        const friendId = $(this).data("id");
        selectFriend(friendId);

        // 切换到聊天面板
        const chatPanel = document.querySelector('.col-6');
        chatPanel.scrollIntoView({ behavior: 'smooth' });
    });
}

// 高亮搜索关键词
function highlightKeyword(text, keyword) {
    const regex = new RegExp(keyword, 'gi');
    return text.replace(regex, match => `<span class="bg-yellow-200">${match}</span>`);
}

// 连接WebSocket
function connectWebSocket() {
    try {
        // 注意：实际使用时需要替换为真实的WebSocket服务器地址
        ws = new WebSocket("ws://127.0.0.1:6868");

        ws.onopen = function() {
            console.log("WebSocket连接已建立");
            // let uid = Math.floor(Math.random() * 1000);
            let uid = 8;

            // 发送连接成功消息
            const messageData = {
                type: "login", //连接登录
                uid: uid, // 登录uid
                message: uid+'我来了',
            };

            ws.send(JSON.stringify(messageData));
        };

        ws.onmessage = function(event) {
            if (event.data !== '连接成功...'){
                const data = JSON.parse(event.data);
                switch (data.type) {
                    case "send_to_uid":
                        receiveMessage(data.uid, data.message, data.message_type);
                        break;
                    case "read":
                        // 更新消息状态为已读
                        updateMessageStatus(data.message_id, "read");
                        break;
                    case 'error_msg':
                        // alert(data.message);
                        break;
                    default:
                        console.log("未知消息类型:", data.type);
                }
            }

        };

        ws.onclose = function() {
            console.log("WebSocket连接已关闭");
            // 尝试重新连接
            setTimeout(connectWebSocket, 3000);
        };

        ws.onerror = function(error) {
            console.error("WebSocket错误:", error);
        };
    } catch (error) {
        console.error("创建WebSocket连接失败:", error);
    }
}

// 更新消息状态
function updateMessageStatus(messageId, status) {
    if (!currentFriendId || !messages[currentFriendId]) return;

    const index = messages[currentFriendId].findIndex(m => m.id === messageId);
    if (index !== -1) {
        messages[currentFriendId][index].status = status;
        showMessages(currentFriendId);
    }
}

// 绑定事件
function bindEvents() {
    // 发送消息按钮点击事件
    $("#send-btn").click(function() {
        const message = $("#message-input").val();
        sendMessage(message);
    });

    // 按Enter发送消息
    $("#message-input").keypress(function(e) {
        if (e.which === 13) {
            e.preventDefault();
            const message = $(this).val();
            sendMessage(message);
        }
    });

    // 表情按钮点击事件
    $("#emoji-btn").click(function() {
        $("#emoji-picker").toggle();
        $("#image-upload").hide();
    });

    // 图片按钮点击事件
    $("#image-btn").click(function() {
        $("#image-upload").toggle();
        $("#emoji-picker").hide();
    });

    // 图片文件选择事件
    $("#image-file").change(function(e) {
        const file = e.target.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = function(event) {
            // 注意：实际使用时应将图片上传到服务器，这里使用data URL作为示例
            sendMessage(event.target.result, "image");
        };
        reader.readAsDataURL(file);
    });

    // 搜索输入事件
    $("#search-input").keyup(function() {
        const keyword = $(this).val();
        searchMessages(keyword);
    });
}
    